package com.hyy.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Redis工具类，封装了对Redis的常用操作，简化了Redis的使用。
 */
@Slf4j
public class Redis {


    private StringRedisTemplate stringRedisTemplate;
    private static final String REDIS_SPLIT = ":";
    private static final String REDIS_DEFAULT_PREFIX = "default";

    public Redis(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * redis get*/
    public String get(String key) {
        try {
            return key == null ? null : stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("redis get error,key:{}", key);
            return null;
        }
    }

    /*true 存在
     * has key 是否存在key*/
    public boolean hasKey(String key) {
        try {
            return key == null?false : stringRedisTemplate.hasKey(key);
        }catch (Exception e) {
            log.error("redis get error,key:{}", key);
            return false;
        }
    }

    /*
     *
     * set key*/
    public boolean set(String key, String value) {
        try{
            if(key==null||value==null){return false;}

            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e) {
            log.error("redis set error,key:{},value:{},e:{}", key, value,e);
            return false;
        }
    }

    /*
    *单位为秒
    * set key*/
    public boolean set(String key, String value,long timeout) {
        try{
            if(key==null||value==null){return false;}

                if(timeout==0){
                    stringRedisTemplate.opsForValue().set(key,value,timeout, TimeUnit.SECONDS);
                }else{
                    set(key,value);
                }
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e) {
            log.error("redis set error,key:{},value:{}", key, value);
            return false;
        }
    }

    public  String buildKey(String prefix,String... args){
        if(prefix==null){
            prefix=REDIS_DEFAULT_PREFIX;
        }
        StringBuilder key=new StringBuilder();
        key.append(prefix);
        if(args!=null){
            for(String arg:args){
                key.append(REDIS_SPLIT).append(arg);
            }
        }
        return key.toString();
    }
}
